// -----------------------------------------------------------------------
//  <copyright file="RoleSeeder.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/10 20:05:07</last-date>
// -----------------------------------------------------------------------

using Liuliu.Fsb.Services.Identity.Domain.Entities;
using Liuliu.Fsb.Services.Identity.Domain.IntegrationEvents;

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;

using OSharp.Collections;


namespace Liuliu.Fsb.Services.Identity.Application.Identity.Roles.Seeds;

public class RoleSeeder(IServiceProvider provider) : EntitySeederBase<Role>(provider)
{
    /// <summary>
    /// 重写以提供要初始化的种子数据
    /// </summary>
    /// <param name="scopedProvider"></param>
    /// <returns></returns>
    protected override Task<Role[]> SeedDataAsync(IServiceProvider scopedProvider)
    {
        var list = new Role[]
        {
            new() { Name = "系统管理员", Remark = "系统最高权限管理角色", IsAdmin = true, IsSystem = true }
        };
        return Task.FromResult(list);
    }

    protected override ISpecification<Role> ExistingSpecification(Role entity)
    {
        return new RoleByNameSpec<Role>(entity.Name);
    }

    protected override async Task SyncToDatabaseAsync(IServiceProvider scopedProvider, Role[] entities)
    {
        if (entities.IsNullOrEmpty())
        {
            return;
        }

        var uow = scopedProvider.GetUnitOfWork(true);
        var roleManager = scopedProvider.GetRequiredService<RoleManager<Role>>();
        var addRoles = new List<RoleInRecord>();
        foreach (var entity in entities)
        {
            var exist = await roleManager.RoleExistsAsync(entity.Name);
            if (exist)
            {
                continue;
            }

            await roleManager.CreateAsync(entity);
            addRoles.Add(new RoleInRecord(entity.Id, entity.Name, entity.IsLocked));
        }

        uow.AddIntegrationEvent(new RoleCreatedIntegrationEvent(addRoles.ToArray()));
        await uow.CommitAsync();
    }
}
